package b0.controller;

import b0.bean.ResultInfo;
import b0.entity.Writer;
import b0.repository.WriterRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/writer")
public class WriterController {

    @Autowired
    WriterRepository writerRepository;


    @GetMapping("/{id}")
    public ResultInfo getPoem(@PathVariable("id") Integer id) {
        ResultInfo resultInfo = new ResultInfo();
        Writer writer = writerRepository.getOne(id);
        resultInfo.setData(writer);
        return resultInfo;
    }

    //增加
    @PostMapping("/add")
    public ResultInfo addWriter(Writer writer) {
        ResultInfo resultInfo = new ResultInfo();
        if ((writer.getContent() != null)&&(writer.getDynasty() != null)){
            Writer save = writerRepository.save(writer);
            resultInfo.setStatus(200);
            resultInfo.setMsg("成功添加");
            resultInfo.setData(save);

        } else {
            resultInfo.setStatus(400);
            resultInfo.setMsg("添加失败");
            resultInfo.setData(writer);
        }
        return resultInfo;
    }

    //删除
    @DeleteMapping("/delete/{id}")
    public ResultInfo deleteWriter(@PathVariable("id")Integer id){
        ResultInfo resultInfo =new ResultInfo();
        writerRepository.deleteById(id);
        resultInfo.setStatus(200);
        resultInfo.setMsg("成功删除");
        return resultInfo;
    }


    @PutMapping("/update")
    public ResultInfo updateWriter(Writer writer){
        ResultInfo resultInfo = new ResultInfo();
        if ((writer.getName() != null)&&(writer.getDynasty() != null)){
            Writer save = writerRepository.save(writer);
            resultInfo.setStatus(200);
            resultInfo.setMsg("成功更新");
            resultInfo.setData(save);

        } else {
            resultInfo.setStatus(400);
            resultInfo.setMsg("添加失败");
            resultInfo.setData(writer);
        }
        return resultInfo;
    }
}
